package xj.graph2d.app.prop;

import static xj.graph2d.app.resources.Resources.getResourceString;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;

import xj.graph2d.Command;
import xj.graph2d.DrawAttr;
import xj.graph2d.DrawCanvas;
import xj.graph2d.DrawShape;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.app.DrawAction;
import xj.graph2d.app.DrawApp;
import xj.graph2d.command.SetAttrCommand;

public class ColorSelectionListener 
  extends DrawAction 
  implements ActionListener {

  @Override
  protected void init() {
    Object ic = DrawApp.getIcon("colorIcon");
    if (ic instanceof ColorIcon) {
      icon = (ColorIcon) ic;
    }
  }

  public void actionPerformed(ActionEvent e) {
    SimpleDrawDocument doc = main.getDoc();
    SimpleDrawView view = main.getView();
    attr = view.getDrawAttr();
    if (attr != null) {
      if (dialog == null) {
	dialog = new ColorSelectionPanel(main.getJFrame(), 
					 getResourceString("ColorDialog.title"), 
					 attr.getPenColor());
      } else {
	dialog.setColor(attr.getPenColor());
      }

      AbstractButton button = null;
      if (source instanceof AbstractButton) {
	button = (AbstractButton) source;
      }

      boolean okay = dialog.showOptionDialog();

      if (button != null) {
	button.setSelected(false);
      }

      if (okay && attr != null) {
	// update system attribute
	attr.setPenColor(dialog.getColor());
	if (icon != null) {
	  icon.setColor(dialog.getColor());
	  if (button != null) {
	    button.repaint();
	  }
	}
	// update current shape
	if (doc != null) {
	  DrawShape curShape = doc.getSelectedShape();
	  if (curShape != null) {
	    DrawAttr curAttr = curShape.getDrawAttr();
	    if (curAttr != null) {
	      Command cmd = new SetAttrCommand(view, doc, curShape);
	      doc.addCommand(cmd);

	      curAttr.setPenColor(dialog.getColor());
	      curShape.calculateBounds();
	      DrawCanvas canvas = view.getCanvas();
	      canvas.repaintShape(curShape);
	    }
	  }
	}
      }
    }
  }

  protected ColorIcon icon = null;

  protected DrawAttr attr = null;

  protected ColorSelectionPanel dialog = null;

}
